"use client"

import React, { useState } from "react"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { Slider } from "@/components/ui/slider"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"

interface ColorPickerProps {
  color: string
  onChange: (color: string) => void
  className?: string
}

export function ColorPicker({ color, onChange, className }: ColorPickerProps) {
  const [hue, setHue] = useState(0)
  const [saturation, setSaturation] = useState(100)
  const [lightness, setLightness] = useState(50)
  const [hexValue, setHexValue] = useState(color)
  
  // Convert HSL to Hex
  const hslToHex = (h: number, s: number, l: number) => {
    s /= 100
    l /= 100
    
    const c = (1 - Math.abs(2 * l - 1)) * s
    const x = c * (1 - Math.abs(((h / 60) % 2) - 1))
    const m = l - c / 2
    let r = 0, g = 0, b = 0
    
    if (0 <= h && h < 60) {
      r = c; g = x; b = 0
    } else if (60 <= h && h < 120) {
      r = x; g = c; b = 0
    } else if (120 <= h && h < 180) {
      r = 0; g = c; b = x
    } else if (180 <= h && h < 240) {
      r = 0; g = x; b = c
    } else if (240 <= h && h < 300) {
      r = x; g = 0; b = c
    } else if (300 <= h && h < 360) {
      r = c; g = 0; b = x
    }
    
    r = Math.round((r + m) * 255)
    g = Math.round((g + m) * 255)
    b = Math.round((b + m) * 255)
    
    const rHex = r.toString(16).padStart(2, '0')
    const gHex = g.toString(16).padStart(2, '0')
    const bHex = b.toString(16).padStart(2, '0')
    
    return `#${rHex}${gHex}${bHex}`
  }
  
  // Update color from HSL sliders
  const updateFromHSL = () => {
    const newColor = hslToHex(hue, saturation, lightness)
    setHexValue(newColor)
    onChange(newColor)
  }
  
  // Update color from hex input
  const updateFromHex = (hex: string) => {
    setHexValue(hex)
    if (/^#[0-9A-F]{6}$/i.test(hex)) {
      onChange(hex)
    }
  }
  
  // Predefined colors
  const presetColors = [
    "#000000", // Black
    "#FFFFFF", // White
    "#FF0000", // Red
    "#00FF00", // Green
    "#0000FF", // Blue
    "#FFFF00", // Yellow
    "#FF00FF", // Magenta
    "#00FFFF", // Cyan
    "#FFA500", // Orange
    "#800080", // Purple
    "#A52A2A", // Brown
    "#808080", // Gray
    "#FFB6C1", // Light Pink
    "#90EE90", // Light Green
    "#ADD8E6", // Light Blue
    "#F0E68C", // Khaki
  ]
  
  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          className={cn("w-10 h-10 p-0 border-2", className)}
          style={{ backgroundColor: color }}
        />
      </PopoverTrigger>
      <PopoverContent className="w-64">
        <Tabs defaultValue="picker">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="picker">Picker</TabsTrigger>
            <TabsTrigger value="sliders">Sliders</TabsTrigger>
            <TabsTrigger value="presets">Presets</TabsTrigger>
          </TabsList>
          
          <TabsContent value="picker" className="mt-2">
            <div className="w-full h-32 mb-2 relative rounded overflow-hidden">
              <div
                className="absolute inset-0"
                style={{
                  background: `linear-gradient(to right, #fff, hsl(${hue}, 100%, 50%))`,
                }}
              />
              <div
                className="absolute inset-0"
                style={{
                  background: "linear-gradient(to top, #000, transparent)",
                }}
              />
            </div>
            <div className="mb-2">
              <Slider
                value={[hue]}
                min={0}
                max={360}
                step={1}
                onValueChange={(value) => {
                  setHue(value[0])
                  updateFromHSL()
                }}
                className="w-full h-4"
                style={{
                  background:
                    "linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)",
                }}
              />
            </div>
            <div className="flex items-center space-x-2">
              <Input
                value={hexValue}
                onChange={(e) => updateFromHex(e.target.value)}
                className="font-mono"
              />
            </div>
          </TabsContent>
          
          <TabsContent value="sliders" className="mt-2 space-y-2">
            <div>
              <label className="text-xs font-medium">Hue: {hue}°</label>
              <Slider
                value={[hue]}
                min={0}
                max={360}
                step={1}
                onValueChange={(value) => {
                  setHue(value[0])
                  updateFromHSL()
                }}
                className="w-full"
                style={{
                  background:
                    "linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)",
                }}
              />
            </div>
            <div>
              <label className="text-xs font-medium">Saturation: {saturation}%</label>
              <Slider
                value={[saturation]}
                min={0}
                max={100}
                step={1}
                onValueChange={(value) => {
                  setSaturation(value[0])
                  updateFromHSL()
                }}
                className="w-full"
                style={{
                  background: `linear-gradient(to right, hsl(${hue}, 0%, 50%), hsl(${hue}, 100%, 50%))`,
                }}
              />
            </div>
            <div>
              <label className="text-xs font-medium">Lightness: {lightness}%</label>
              <Slider
                value={[lightness]}
                min={0}
                max={100}
                step={1}
                onValueChange={(value) => {
                  setLightness(value[0])
                  updateFromHSL()
                }}
                className="w-full"
                style={{
                  background: `linear-gradient(to right, #000, hsl(${hue}, ${saturation}%, 50%), #fff)`,
                }}
              />
            </div>
          </TabsContent>
          
          <TabsContent value="presets" className="mt-2">
            <div className="grid grid-cols-4 gap-2">
              {presetColors.map((presetColor) => (
                <button
                  key={presetColor}
                  className={cn(
                    "w-10 h-10 rounded border border-gray-300",
                    presetColor === color && "ring-2 ring-primary ring-offset-2"
                  )}
                  style={{ backgroundColor: presetColor }}
                  onClick={() => {
                    setHexValue(presetColor)
                    onChange(presetColor)
                  }}
                />
              ))}
            </div>
          </TabsContent>
        </Tabs>
      </PopoverContent>
    </Popover>
  )
}